package com.sita.tboard.hitchhike.detail;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.MyTrafficStyle;
import com.facebook.drawee.view.SimpleDraweeView;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.sita.bike.R;
import com.sita.bike.rest.model.Account;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.support.LocationController;
import com.sita.tboard.hitchhike.HitchhikeActivity;
import com.sita.tboard.hitchhike.HitchhikeConstants;
import com.sita.tboard.hitchhike.HitchhikeContentActivity;
import com.sita.tboard.hitchhike.bean.TicketModel;
import com.sita.tboard.hitchhike.bean.TicketStatus;
import com.sita.tboard.hitchhike.event.HitchhikeDriverAcceptTripEvent;
import com.sita.tboard.hitchhike.event.HitchhikeTripStatusEvent;
import com.sita.tboard.hitchhike.helper.HitchhikeNetworkHelper;
import com.sita.tboard.hitchhike.listeners.OnPayHitchhikeListener;
import com.sita.tboard.hitchhike.listeners.OnTicketStatusChangeListener;
import com.sita.tboard.ui.tools.L;
import com.sita.tboard.usermgmt.GetAccountInfoListener;
import com.sita.tboard.usermgmt.helper.UserNetworkHelper;
import com.sita.tboard.util.DateUtils;
import com.sita.tboard.util.TextUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;
import cn.trinea.android.common.util.ToastUtils;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;

public class PassengerTripDetailActivity extends HitchhikeContentActivity
        implements LocationSource, AMapLocationListener, AMap.OnMapLoadedListener {

    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.btn_cancel)
    TextView mCancel;
    @Bind(R.id.avatar)
    SimpleDraweeView mAvatarView;
    @Bind(R.id.btn_dialer)
    CircleImageView mDialerView;
    @Bind(R.id.nickname)
    TextView mNicknameView;
    @Bind(R.id.time)
    TextView mTimeView;
    @Bind(R.id.from)
    TextView mFromView;
    @Bind(R.id.to)
    TextView mToView;
    @Bind(R.id.map)
    MapView mapView;
    @Bind(R.id.driver_line)
    LinearLayout mDriverLayout;
    @Bind(R.id.remain_layout)
    LinearLayout mRemainLayout;
    @Bind(R.id.remain)
    cn.iwgang.countdownview.CountdownView mRemainView;
    @Bind(R.id.btn_pay)
    Button mPayBtn;

    private TicketModel mTicket;
    private AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;

    private Marker fromMarker;
    private Marker driverMarker;
    private boolean isStartLocating;

    private Account driverAccount;

    private Context mContext;

    @SuppressWarnings("unused")
    public static Intent newIntent(TicketModel ticket) {
        Intent intent = new Intent(GlobalContext.getGlobalContext(), PassengerTripDetailActivity.class);
        intent.putExtra("ticket", ticket);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hitchhike_passenger_trip_detail);
        ButterKnife.bind(this);

        mContext = this;

        mapView.onCreate(savedInstanceState);

        mTicket = (TicketModel) getIntent().getSerializableExtra("ticket");
        if (mTicket == null) {
            L.e("Does not have a bundled ticket");
            finish();
            return;
        }
        customizeToolbar(mToolbar, TicketStatus.getInstance().getStatus(mTicket.status));

        initTicket();
        initDriver();
        initMap();

        setupButtons();
    }

    private void initTicket() {
        mTimeView.setText(GlobalContext.getGlobalContext().getString(R.string.departure_time,
                DateUtils.formatDateTime(mTicket.orderDepartureTime)));
        mFromView.setText(GlobalContext.getGlobalContext().getString(R.string.from, mTicket.fromaddress));
        mToView.setText(GlobalContext.getGlobalContext().getString(R.string.to, mTicket.toaddress));

        mRemainView.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                HitchhikeNetworkHelper.INSTANCE.cancelPassengerTicket(mTicket.id, new OnTicketStatusChangeListener() {
                    @Override
                    public void onSuccess() {
                        DialogPlus.newDialog(mContext)
                                .setCancelable(false)
                                .setGravity(Gravity.CENTER)
                                .setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.dialog_hitchhike_passenger_expire_cancel))
                                .setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(final DialogPlus dialog, View view) {
                                        if (view.getId() == R.id.btn_ok) {
                                            dialog.dismiss();
                                            startActivity(HitchhikeActivity.newIntent(HitchhikeConstants.TAG_PASSENGER_RUNNING));
                                            finish();
                                        }
                                    }
                                })
                                .create().show();
                    }

                    @Override
                    public void onFailure(Throwable throwable) {

                    }
                });
            }
        });

        updateToolbarTitle(TicketStatus.getInstance().getStatusTitle(mTicket.status));

        if (mTicket.status != TicketStatus.getInstance().UNKNOWN
                && mTicket.status != TicketStatus.getInstance().WAITING
                || mTicket.status == TicketStatus.getInstance().CANCELED) {
            mDriverLayout.setVisibility(View.VISIBLE);
            mRemainLayout.setVisibility(View.GONE);

            mRemainView.stop();
        } else {
            mDriverLayout.setVisibility(View.GONE);
            mRemainLayout.setVisibility(View.VISIBLE);

            mRemainView.start(HitchhikeConstants.DEFAULT_FUTURE_TIME);
        }
        if (mTicket.status == TicketStatus.getInstance().UNPAID){
            DialogPlus.newDialog(this)
                    .setCancelable(false)
                    .setGravity(Gravity.TOP)
                    .setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.dialog_hitchhike_passenger_pay))
                    .setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(final DialogPlus dialog, View view) {
                            if (view.getId() == R.id.btn_pay) {
                                AutoCompleteTextView moneyView = (AutoCompleteTextView)dialog.findViewById(R.id.payment);
                                String money = moneyView.getText().toString();
                                if (!android.text.TextUtils.isEmpty(money)){
                                    HitchhikeNetworkHelper.INSTANCE.passengerPayTrip(String.valueOf(mTicket.id),
                                            Float.valueOf(money), new OnPayHitchhikeListener() {
                                                @Override
                                                public void onSuccess() {
                                                    startActivity(HitchhikeActivity.newIntent(HitchhikeConstants.TAG_PASSENGER_RUNNING));
                                                    dialog.dismiss();
                                                }

                                                @Override
                                                public void onFailure(Throwable throwable) {
                                                    ToastUtils.show(GlobalContext.getGlobalContext(),
                                                            com.sita.tboard.util.TextUtils.getThrowableMessage(throwable));
                                                }
                                            });
                                }
                            }
                        }
                    })
                    .create().show();
        }
    }

    private void initDriver() {
        if (mTicket.driverId != null) {
            UserNetworkHelper.getInstance().getUserInfo(String.valueOf(mTicket.driverId),
                    new GetAccountInfoListener() {
                        @Override
                        public void onSuccess(Account account) {
                            driverAccount = account;
                            //Picasso.with(GlobalContext.getGlobalContext()).load(account.mAvatar).into(mAvatarView);
                            mAvatarView.setImageURI(account.mAvatar != null ? Uri.parse(account.mAvatar) : Uri.EMPTY);
                            mNicknameView.setText(account.mNickName);
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            ToastUtils.show(GlobalContext.getGlobalContext(),
                                    TextUtils.getThrowableMessage(throwable));
                        }
                    });
        }
    }

    /**
     * 初始化AMap对象
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();

            aMap.setOnMapLoadedListener(this);
            aMap.setLocationSource(this);

            UiSettings mUiSettings = aMap.getUiSettings();
            mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_CENTER);
            mUiSettings.setZoomControlsEnabled(true);
            mUiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
            mUiSettings.setMyLocationButtonEnabled(false);
            mUiSettings.setAllGesturesEnabled(true);
            mUiSettings.setCompassEnabled(true);
            aMap.setMyTrafficStyle(new MyTrafficStyle());
            aMap.setMyLocationEnabled(true);
            aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);

            MyLocationStyle myLocationStyle = new MyLocationStyle();
            myLocationStyle.myLocationIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));// 设置小蓝点的图标
            myLocationStyle.strokeColor(Color.BLUE);// 设置圆形的边框颜色
            myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
            myLocationStyle.strokeWidth(0.5f);// 设置圆形的边框粗细

            aMap.setMyLocationStyle(myLocationStyle);

            aMap.animateCamera(CameraUpdateFactory.zoomTo(12));
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int status = mTicket.status;
        switch (item.getItemId()) {
            case android.R.id.home: {
                if (status == TicketStatus.getInstance().PAID) {
                    finish();
                } else {
                    startActivity(HitchhikeActivity.newIntent(HitchhikeConstants.TAG_PASSENGER_RUNNING));
                    finish();
                }
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
            aMap = null;
        }
        LocationController.stopTracking(this);
    }

    /**
     * 开始定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (!isStartLocating) {
            LocationController.startTracking(this);
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        LocationController.stopTracking(this);
    }

    @Override
    public void onMapLoaded() {
        initMarkers();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation.getErrorCode() == 0) {
            mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
        }
        //判断定位是否成功
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            return;
        }
        //是否已经开始定位
        isStartLocating = true;

        //是否开始显示自己，小蓝点
        //地点的纬度，在-90 与90 之间的double 型数值
        double latitude = aMapLocation.getLatitude();
        //地点的经度，在-180 与180 之间的double 型数值
        double longitude = aMapLocation.getLongitude();
        //角标显示的位置
        LatLng myLatLng = new LatLng(latitude, longitude);
        // 设置地图可视缩放大小
        //aMap.animateCamera(CameraUpdateFactory.changeLatLng(latLng));
        LatLngBounds bounds = new LatLngBounds.Builder().include(fromMarker.getPosition())
                .include(myLatLng).build();
        // 移动地图，所有marker自适应显示。LatLngBounds与地图边缘10像素的填充区域
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
    }

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    private void initMarkers() {
        LatLng fromLatlng = null;
        if (fromMarker == null) {
            fromLatlng = new LatLng(mTicket.startLat, mTicket.startLng);
            MarkerOptions markerOptions = new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.redpin))
                    .draggable(false)
                    .position(fromLatlng);
            fromMarker = aMap.addMarker(markerOptions);
        }

        LatLng myLatlng = getMyLatLng();
        updateMapBounds(fromLatlng, myLatlng, null);
    }

    private void setDriverMarker(double latitude, double longitude) {
        LatLng driverLatlng = new LatLng(latitude, longitude);
        if (driverMarker == null) {
            MarkerOptions markerOptions = new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_motorcycle))
                    .draggable(false)
                    .position(driverLatlng);
            driverMarker = aMap.addMarker(markerOptions);
        } else {
            driverMarker.setPosition(driverLatlng);
        }
        LatLng myLatlng = getMyLatLng();
        updateMapBounds(fromMarker.getPosition(), myLatlng, driverLatlng);
    }

    private void updateMapBounds(LatLng toLatlng, LatLng myLatlng, LatLng driverLatlng) {
        LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder()
                .include(toLatlng);
        if (myLatlng != null) {
            boundsBuilder.include(myLatlng);
        }
        if (driverLatlng != null) {
            boundsBuilder.include(driverLatlng);
        }
        LatLngBounds bounds = boundsBuilder.build();
        // 移动地图，所有marker自适应显示。LatLngBounds与地图边缘10像素的填充区域
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 80));
    }

    private LatLng getMyLatLng() {
        AMapLocation myLocation = LocationController.getLastKnownLocation();
        if (Double.compare(myLocation.getLatitude(), 0) != 0
                && Double.compare(myLocation.getLongitude(), 0) != 0) {
            return new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
        }
        return null;
    }

    @OnClick(R.id.btn_dialer)
    void onClickBtnDialer() {
        String phone = HitchhikeConstants.DEFAULT_PHONE_NUMBER;
        if (!android.text.TextUtils.isEmpty(driverAccount.mMobile)) {
            phone = driverAccount.mMobile;
        }
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phone));
        startActivity(intent);
    }

    @OnClick(R.id.btn_cancel)
    void onClickBtnCancel() {
        if (mTicket.status == TicketStatus.getInstance().WAITING) {
            DialogPlus.newDialog(mContext)
                    .setCancelable(false)
                    .setGravity(Gravity.CENTER)
                    .setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.dialog_hitchhike_passenger_cancel_waiting))
                    .setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(final DialogPlus dialog, View view) {
                            if (view.getId() == R.id.btn_ok) {
                                dialog.dismiss();
                                doCancel();
                            }
                        }
                    })
                    .create().show();
        }
        if (mTicket.status == TicketStatus.getInstance().ACCEPTED) {
            DialogPlus.newDialog(mContext)
                    .setCancelable(false)
                    .setGravity(Gravity.CENTER)
                    .setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.dialog_hitchhike_passenger_cancel_accept))
                    .setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(final DialogPlus dialog, View view) {
                            if (view.getId() == R.id.btn_ok) {
                                dialog.dismiss();
                                doCancel();
                            }
                        }
                    })
                    .create().show();
        }
    }

    @OnClick(R.id.btn_pay)
    void onClickBtnPay() {
        DialogPlus.newDialog(this)
                .setCancelable(false)
                .setGravity(Gravity.TOP)
                .setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.dialog_hitchhike_passenger_pay))
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(final DialogPlus dialog, View view) {
                        if (view.getId() == R.id.btn_pay) {
                            AutoCompleteTextView moneyView = (AutoCompleteTextView) dialog.findViewById(R.id.payment);
                            String dollar = moneyView.getText().toString();
                            HitchhikeNetworkHelper.INSTANCE
                                    .passengerPayTrip(String.valueOf(mTicket.id), Float.valueOf(dollar), new OnPayHitchhikeListener() {
                                        @Override
                                        public void onSuccess() {
                                            startActivity(HitchhikeActivity.newIntent(HitchhikeConstants.TAG_PASSENGER_RUNNING));
                                            PassengerTripDetailActivity.this.finish();
                                        }

                                        @Override
                                        public void onFailure(Throwable throwable) {
                                            ToastUtils.show(GlobalContext.getGlobalContext(), TextUtils.getThrowableMessage(throwable));
                                        }
                                    });
                            dialog.dismiss();
                        }
                    }
                })
                .create().show();
    }

    private void setupButtons() {
        if (mTicket.status == TicketStatus.getInstance().WAITING) {
            mCancel.setVisibility(View.VISIBLE);
            mPayBtn.setVisibility(View.GONE);
        } else if (mTicket.status == TicketStatus.getInstance().UNPAID) {
            mCancel.setVisibility(View.GONE);
            mPayBtn.setVisibility(View.VISIBLE);
            mPayBtn.setClickable(true);
            mPayBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_background));
        } else if (mTicket.status == TicketStatus.getInstance().START) {
            mCancel.setVisibility(View.GONE);
            mPayBtn.setVisibility(View.VISIBLE);
            mPayBtn.setClickable(false);
            mPayBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_background_disabled));
        } else {
            mPayBtn.setVisibility(View.GONE);
            mCancel.setVisibility(View.GONE);
        }
    }

    public void onEventMainThread(final HitchhikeDriverAcceptTripEvent event) {
        final Long tripId = Long.valueOf(event.getRentTripId());
        final Long driverId = Long.valueOf(event.getKnightId());
        DialogPlus.newDialog(this)
                .setCancelable(false)
                .setGravity(Gravity.CENTER)
                .setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.dialog_hitchhike_passenger_trip_accepted))
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(final DialogPlus dialog, View view) {
                        if (view.getId() == R.id.btn_ok) {
                            mTicket.driverId = driverId;
                            mTicket.id = tripId;
                            mTicket.status = TicketStatus.getInstance().ACCEPTED;

                            mDriverLayout.setVisibility(View.VISIBLE);
                            mRemainLayout.setVisibility(View.GONE);
                            mRemainView.stop();

                            updateToolbarTitle(TicketStatus.getInstance().getStatusTitle(mTicket.status));

                            setDriverMarker(event.getLat(), event.getLng());

                            setupButtons();

                            dialog.dismiss();
                        }
                    }
                })
                .create().show();
    }

    public void onEventMainThread(HitchhikeTripStatusEvent event) {
        mCancel.setVisibility(View.GONE);
        mTicket.status = event.getStatus();

        updateToolbarTitle(TicketStatus.getInstance().getStatusTitle(mTicket.status));

        setupButtons();
    }

    private void doCancel(){
        HitchhikeNetworkHelper.INSTANCE.cancelPassengerTicket(mTicket.id, new OnTicketStatusChangeListener() {
            @Override
            public void onSuccess() {
                startActivity(HitchhikeActivity.newIntent(HitchhikeConstants.TAG_PASSENGER_RUNNING));
                finish();
            }

            @Override
            public void onFailure(Throwable throwable) {
                ToastUtils.show(GlobalContext.getGlobalContext(), TextUtils.getThrowableMessage(throwable));
            }
        });
    }
}
